# -*- coding: utf-8 -*-
import locale
import os
import urllib2


def to_unicode(text):
	if isinstance(text, unicode):
		return text

	if hasattr(text, '__unicode__'):
		return text.__unicode__()

	text = str(text)

	try:
		return unicode(text, 'utf-8')
	except UnicodeError:
		pass

	try:
		return unicode(text, locale.getpreferredencoding())
	except UnicodeError:
		pass

	return unicode(text, 'latin1')


def download_image(url, filepath):
	if not os.path.isdir(os.path.dirname(filepath)):
		os.makedirs(os.path.dirname(filepath))
	fd = file(filepath, "wb+")
	try:
		fd.write(urllib2.urlopen(url).read())
	finally:
		fd.close()


